package bb.lanxing.fragment.team;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.material.tabs.TabLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.mylhyl.circledialog.CircleDialog;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.team.EventSearchActivity;
import bb.lanxing.activity.team.TeamCreateActivity;
import bb.lanxing.adapter.team.TeamAdapter;
import bb.lanxing.common.config.Constants;
import bb.lanxing.fragment.base.BaseTabFragment;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import okhttp3.Call;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class TeamFragment extends BaseTabFragment {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private TeamAdapter adapter;

    public TeamFragment() {
        super(R.layout.fragment_team);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_team, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.add_button).setOnClickListener(v -> {
            if (App.getContext().isUserSignin()) {
                if (TextUtils.isEmpty(App.getContext().getUserPhone())) {
                    // App.getContext().userBindPhone();
                }
                if (App.getContext().getSigninUser().getTencentIm() == null
                        || "0".equals(App.getContext().getSigninUser().getTencentIm())) {
                    showTeamDialog();
                } else {
                    startActivityForResult(new Intent(getActivity(), TeamCreateActivity.class), Constants.REQUEST_CODE);
                }
            } else {
                App.getContext().userSignin();
            }
        });
        view.findViewById(R.id.search_button)
                .setOnClickListener(v -> startActivity(new Intent(getActivity(), EventSearchActivity.class)));

        tabLayout = view.findViewById(R.id.tabLayout);
        viewPager = view.findViewById(R.id.pager);

        adapter = new TeamAdapter(getChildFragmentManager());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onResume() {
        super.onResume();
        ImmersionBar.with(this).transparentStatusBar().statusBarDarkFont(true).init();
    }

    private void showTeamDialog() {
        new CircleDialog.Builder().setTitle(getString(R.string.main_team))
                .setText(getString(R.string.team_permission_content)).setPositive(getString(R.string.apply), v -> {
                    requestUserTencentImAccount(App.getContext().getSigninUser().getPhone());
                    return true;
                }).show(getParentFragmentManager());
    }

    private void requestUserTencentImAccount(String phone) {
        Call call = MyHttpClient.bindTencentIM(phone);
        showLoadingDialog(R.string.map_handling_share, true);
        Observable.create(new NetSubscribe(call)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast(getString(R.string.failed_apply));
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                                if (200 == code) {
                                    toast(getString(R.string.successed_apply));
                                    startActivityForResult(new Intent(getActivity(), TeamCreateActivity.class),
                                            Constants.REQUEST_CODE);
                                }
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast(getString(R.string.failed_apply));
                        }
                    }
                });
    }
}
